import java.net.*;
import java.util.*;

public class Room {
	
	public String name;
	public ArrayList<Socket> users = new ArrayList<Socket>();
	public long max=6;
	private DataServer server;
	
	public Room(String name, long l, DataServer server) {
		this.name = name;
		this.max = l;
		this.server = server;
		server.roomnames.put(name, this);
		server.sendToRoom("CREATEROOM:" + name, "Lobby");
	}
	
	public void addUser(Socket socket) {
		if (users.size()<=max) {
			String username = server.usernames.get(socket);
			synchronized(users) {
				// Notify other members of the room about the newcomer
				users.add(socket);
				server.rooms.put(socket, this);
				if (name.equals("Lobby")) {
					server.sendToRoom("LOBBYUSERJOIN:" + username, name);
				} else {
					server.sendToRoom("USERJOIN:" + username, name);
				}
				
				
				// Notify the newcomer of the other members
				String usernames = "";
				for (int i=0; i<users.size(); i++) {
					usernames += server.usernames.get(users.get(i)) + "|";
				}
				if (name.equals("Lobby")) {
					server.sendToSocket("LOBBYUSERLIST:" + usernames, socket);
				} else {
					server.sendToSocket("USERLIST:" + usernames, socket);
				}
				
				if (name.equals("Lobby")) {
					// If this is the lobby, notify newcomer of the available rooms
					String roomlist = "";
					Enumeration<String> roomnames = server.roomnames.keys();
					while (roomnames.hasMoreElements()) {
						String next_room = roomnames.nextElement();
						if (!next_room.equals("Lobby"))
							roomlist += next_room + "|";
					}
					server.sendToSocket("LOBBYROOMLIST:" + roomlist, socket);
				}
			}
		}
	}
	
	public void delUser(Socket socket) {
		users.remove(socket);
		if (name.equals("Lobby")) {
			String username = server.usernames.get(socket);
			server.sendToRoom("LOBBYUSERLEFT:" + username, "Lobby");
		} else if (users.size() > 0) {
			String username = server.usernames.get(socket);
			server.sendToRoom("USERLEFT:" + username, name);
		} else {
			server.roomnames.remove(name);
			server.sendToRoom("DELETEROOM:" + name, "Lobby");
		}
		server.roomnames.remove(socket);
	}
}
